﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Collections.Concurrent;
using static drawDong.WriteWorker;

namespace drawDong
{
    public partial class MainReplace : Form
    {
        private string rootPath;
        private ArrayList filesCehck;
        private ArrayList dLines = new ArrayList();//文件下面所有的数据
        private int rowCount = 0;
        private ArrayList dLinesCheck = new ArrayList();
        private int itemSize = 0, itemSizeDown = 0;
        private System.Threading.SynchronizationContext mainThreadSynContext;
        private ArrayList filePathList = ArrayList.Synchronized(new ArrayList());
        private int filesSize = 0, folderPathSize = 0;
        private bool isLoadFilePathEnd = false;
        private ArrayList replaceContentList = new ArrayList();

        class FileRepInfo
        {
            public string path = "";
            public int itemSize = 0;
            public int itemSizeDown = 0; 
            public ArrayList dLines = new ArrayList();
            public ArrayList dLinesCheck = new ArrayList();
        }

        public MainReplace(string path, ArrayList files)
        {
            InitializeComponent();
            this.rootPath = path;
            this.filesCehck = files;
        }

        private void MainReplace_Load(object sender, EventArgs e)
        {
            mainThreadSynContext = System.Threading.SynchronizationContext.Current;
            System.Threading.Thread th = new System.Threading.Thread(loadFilePathStart);
            th.Start();
        }

        private void loadFilePathStart()
        {
            foreach (string di in filesCehck)
            {
                loadFilePath(this.rootPath + @"\" + di);
            }
            isLoadFilePathEnd = true;
            folderPathSize = filePathList.Count;
        }

        private void loadFilePath(string path)
        {
            //创建文件夹
            DirectoryInfo rootDir = new DirectoryInfo(path);
            Boolean exists = Directory.Exists(path);
            if (exists == false)//判断目录是否存在
            {
                return;
            }
            DirectoryInfo[] folders = rootDir.GetDirectories();
            foreach (DirectoryInfo di in folders)
            {
                loadFilePath(di.FullName);
            }
            if (folders.Length <= 0)
            {
                FileRepInfo fri = new FileRepInfo();
                fri.path = path;
                filePathList.Add(fri);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string content = this.textBox1.Text.ToString().Trim();
            if (content.Length == 0)
            {
                MessageBox.Show("请输入一个数字", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            }
            else
            {
                if (isLoadFilePathEnd == false)
                {
                    MessageBox.Show("文件列表读取中...", "提示");
                    return;
                }
                this.label1.Text = DateTime.Now.ToLongTimeString();
                this.button1.Enabled = false;
                this.button2.Enabled = false;

                new System.Threading.Thread(replace).Start();
            }
        }

        private void threadCallBack(object state)
        {
            ++filesSize;
            this.label2.Text = DateTime.Now.ToLongTimeString() + "----文件数----" + filesSize;
            int m = filesSize * 100 / folderPathSize;
            this.progressBar1.Value = m > 100 ? 100 : m;
            if (filesSize != folderPathSize)
            {
                return;
            }

            this.button1.Enabled = true;
            this.button2.Enabled = true;
            if (MessageBox.Show("已替换") == DialogResult.OK)
            {
                this.WindowState = FormWindowState.Minimized;
                new System.Threading.Thread(appendContent).Start();
            }
        }

        private void thrCallBack(object state)
        {
            this.label2.Text = DateTime.Now.ToLongTimeString();
        }

        private void replace()
        {
            string content = this.textBox1.Text.ToString().Trim();
         
            while (filePathList.Count > 0)
            {
                FileRepInfo fri;
                lock (filePathList.SyncRoot)
                {
                    fri = (FileRepInfo)filePathList[0];
                    filePathList.RemoveAt(0);
                }
                bianLiNext(fri.path, content, fri);

                mainThreadSynContext.Post(new System.Threading.SendOrPostCallback(threadCallBack), null);
            }
            Console.WriteLine("over");
        }

        private void replace2()
        {
            string content = this.textBox1.Text.ToString().Trim();

            while (filePathList.Count > 0)
            {
                FileRepInfo fri;
                lock (filePathList.SyncRoot)
                {
                    fri = (FileRepInfo)filePathList[0];
                    filePathList.RemoveAt(0);
                }
                bianLiNext(fri.path, content, fri);

                mainThreadSynContext.Post(new System.Threading.SendOrPostCallback(threadCallBack), null);
            }
            Console.WriteLine("over2");
        }

        private void replace3()
        {
            string content = this.textBox1.Text.ToString().Trim();

            while (filePathList.Count > 0)
            {
                FileRepInfo fri;
                lock (filePathList.SyncRoot)
                {
                    fri = (FileRepInfo)filePathList[0];
                    filePathList.RemoveAt(0);
                }
                bianLiNext(fri.path, content, fri);

                mainThreadSynContext.Post(new System.Threading.SendOrPostCallback(threadCallBack), null);
            }
            Console.WriteLine("over3");
        }

        //private void replace()
        //{
        //    string content = this.textBox1.Text.ToString().Trim();
        //    foreach (string path in filePathList)
        //    {
        //        bianLiNext(path, content);
        //        mainThreadSynContext.Post(new System.Threading.SendOrPostCallback(threadCallBack), null);
        //    }
        //}

        //private void bianLi(string path, string content)
        //{
        //    DirectoryInfo rootDir = new DirectoryInfo(path);
        //    Boolean exists = Directory.Exists(path);
        //    if (exists == false)
        //    {
        //        return;
        //    }
        //    DirectoryInfo[] folders = rootDir.GetDirectories();
        //    foreach (DirectoryInfo di in folders)
        //    {
        //        bianLi(di.FullName, content);
        //    }
        //    if (folders.Length <= 0)
        //    {
        //        bianLiNext(path, content);
        //    }
        //}

        private void bianLiNext(string path, string content, FileRepInfo fri)
        {
            Console.WriteLine("11111----" + path);
            //创建文件夹
            DirectoryInfo rootDir = new DirectoryInfo(path);
            Boolean exists = Directory.Exists(path);
            if (exists == false)//判断目录是否存在
            {
                return;
            }
            FileInfo[] files = rootDir.GetFiles();
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo tit = files[i];
                string filePath = tit.FullName;

                if (filePath.EndsWith("x.txt") == false)
                {
                    continue;
                }
                
                loadData(filePath.Replace("x.txt", ".txt"), fri);
                loadDataDown(filePath, fri);
                handleContent(filePath, content, fri);
                replaceContent(filePath, content, fri);
               
            }
        }

        private void loadDataDown(string fileName, FileRepInfo fri)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
            while (!sr.EndOfStream)
            {
                string[] items = sr.ReadLine().Split(',');
                if (fri.itemSizeDown == 0)
                {
                    fri.itemSizeDown = items.Length;
                }
                break;
            }
            sr.Close();
        }

        private void loadData(string fileName, FileRepInfo fri)
        {
            rowCount = 0;
            dLines.Clear();
            System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
            while (!sr.EndOfStream)
            {
                string[] items = sr.ReadLine().Split(',');
                if (fri.itemSize == 0)
                {
                    fri.itemSize = items.Length;
                }
                
                for (int i = 0; i < items.Length; i++)
                {
                    dLine dline = new dLine();
                    dline.setValue(items[i].Equals("-1") ? "" : items[i]);
                    dline.setCloumnIndex(i);
                    dline.setRowIndex(rowCount);
                    fri.dLines.Add(dline);
                }
                rowCount += 1;

            }
            sr.Close();
        }

        private void handleContent(string path, string content, FileRepInfo fri)
        {
            fri.dLinesCheck.Clear();
            //查询符合要求的字符所在的列
            foreach (dLine item in fri.dLines)
            {
                string itemValue = item.getValue();

                if (null != itemValue && itemValue.Equals(content) && item.getCloumnIndex() < fri.itemSizeDown)
                {
                    int columnIndex = item.getCloumnIndex();
                    if (!fri.dLinesCheck.Contains(columnIndex))
                    {
                        fri.dLinesCheck.Add(columnIndex);
                    }
                }
            }
            fri.dLinesCheck.Sort();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void replaceContent(string path, string content, FileRepInfo fri)
        {
            //生成新的一行数据追加到文件最后
            string[] contents = new string[fri.itemSize];
            int count = fri.dLinesCheck.Count;
            for (int i = 0; i < count; i++)
            {
                int cIndex = (int)fri.dLinesCheck[i];
                contents[cIndex] = content;
            }
            StringBuilder strBuilder = new StringBuilder();
            for (int j = 0; j < contents.Length; j++)
            {
                string con = contents[j];
                if (null == con)
                {
                    con = "";
                }
                strBuilder.Append(con + ",");
            }
            strBuilder.Remove(strBuilder.Length - 1, 1);
            string contentStr = strBuilder.ToString();
            if (contentStr.Length <= 0)
            {
                return;
            }
            RepContent rc = new RepContent();
            rc.path = path;
            rc.contentStr = contentStr;

            replaceContentList.Add(rc);
            fri.dLines.Clear();
            fri.dLinesCheck.Clear();
        }

        private void appendContent()
        {
            WriteWorker.AddRange(replaceContentList);
            replaceContentList.Clear();
            mainThreadSynContext.Post(new System.Threading.SendOrPostCallback(thrWriteCallBack), null);
        }

        private void thrWriteCallBack(object state)
        {
            this.Close();
        }


    }
}
